import React from 'react'
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd'
import store from './store'
import {getInputChangeAction, getAddItemAction, getDeleteItemAction,} from './store/actionCreator'

class TodoList extends React.Component {

    constructor(props) {
        super(props)
        this.state = store.getState()
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleStoreChange = this.handleStoreChange.bind(this)
        this.handleClick = this.handleBtnClick.bind(this)
        //store内的数据发生改变，subscribe内的函数可以自动执行
        store.subscribe(this.handleStoreChange)
    }

    render() {
        return (
            <div style={{ marginTop: '10px', marginLeft: '10px' }}>
                <div>
                    <Input
                        placeholder='todo info'
                        style={{ width: '300px', marginRight: '10px' }}
                        value={this.state.inputValue}
                        onChange={this.handleInputChange}
                    ></Input>
                    <Button
                        type='primary'
                        onClick={this.handleBtnClick}
                    >提交</Button>
                </div>
                <List style={{ marginTop: '10px', width: '300px' }}
                    bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => (
                        <List.Item onClick={this.handleItemDelete.bind(this, index)}>
                            {item}
                        </List.Item>
                    )}
                />
            </div>
        )
    }



    handleStoreChange() {
        this.setState(store.getState())
    }

    handleInputChange(e) {
        // const action = {
        //     type: CHANGE_INPUT_VALUE,
        //     value: e.target.value
        // }
        const action = getInputChangeAction(e.target.value)
        store.dispatch(action)
    }

    handleBtnClick() {
        const action = getAddItemAction()
        store.dispatch(action)
    }

    handleItemDelete(index) {
        const action = getDeleteItemAction(index)
        store.dispatch(action)
    }
}

export default TodoList